import { Device } from "@/api/interface/iot";
import {
	licenseMachine,
	licenseMachineModify,
	machineAdd,
	machineDel,
	machineDownload,
	machineInfoModify
} from "@/api/modules/system/license";
import ProTable from "@/components/ProTable/index.vue";
import { ColumnProps } from "@/components/ProTable/interface";
import { useAuthButtons } from "@/hooks/useAuthButtons";
import { licenseStatusType } from "@/enums/dictEnum";
import "./index.scss";
import DialogBox from "@/components/DialogBox";
import JsonEditerVue from "@/components/JsonForm/JsonEditer.vue";
import { RouterPath } from "@/enums/routerPath";
import { gotoPage } from "@/utils/routerUtil";
import { showTips, confirm, showMsg, exportFile } from "@/utils/util";
import { dayjs, ElMessageBox } from "element-plus";
import { MessageType } from "@/enums/messageEnum";
export default defineComponent({
	setup() {
		const initParam = reactive<Device.ReqProduct>({ pageIndex: 1, pageSize: 20 });
		const proTable = ref<any>();

		const dataCallback = (data: any) => {
			return {
				datalist: data.records,
				total: data.total || 0,
				pageIndex: data.current,
				pageSize: data.size
			};
		};

		const getTableList = async (params: any) => {
			return licenseMachine(params);
		};
		const btnList = ref<any>([]);
		onMounted(async () => {
			// 获取页面按钮权限
			btnList.value = await useAuthButtons();
		});
		const detailDialog = reactive<any>({
			id: "",
			title: "",
			detail: "",
			visible: false
		});
		const addDialog = reactive<any>({
			machineId: "",
			name: "",
			visible: false
		});
		const clickBtn = async (fn: string, row: any) => {
			switch (fn) {
				case "detail":
					detailDialog.id = row.id;
					detailDialog.detail = JSON.stringify(row.license);
					detailDialog.visible = true;
					detailDialog.title = "授权信息";
					break;
				case "sysInfo":
					detailDialog.detail = JSON.stringify(row.sysInfo);
					detailDialog.visible = true;
					detailDialog.title = "系统信息";
					break;
				case "add":
					addDialog.name = "";
					addDialog.machineId = "";
					addDialog.visible = true;
					break;
				case "del":
					confirm({ content: "是否删除该数据！" }).then(async (flag: any) => {
						if (!flag) {
							return;
						}
						let { code, message } = await machineDel({ id: row.id });
						let ok = showTips(code, "删除机器", message);
						if (ok) {
							proTable.value.reset();
						}
					});
					break;
				case "download":
					const res = await machineDownload({ id: row.id });
					exportFile(res);
					break;
			}
		};

		// 表格配置项
		const columns: ColumnProps[] = [
			{ type: "selection", fixed: "left", width: "auto" },
			{ prop: "machineId", label: "机器ID", width: 180, search: { el: "input" } },
			{ prop: "encryptMachineId", label: "加密机器ID", isShow: false, search: { el: "input" } },
			{ prop: "name", label: "名字", search: { el: "input" }, width: 150 },
			{ prop: "os", label: "操作系统", width: 100 },
			{ prop: "ip", label: "IP", width: 120 },
			{ prop: "hostname", label: "主机名", width: 150 },
			{ prop: "version", label: "版本", width: 150 },
			{ prop: "arch", label: "CPU架构", width: 100 },
			{ prop: "times", label: "授权次数", width: 100 },
			{ prop: "expired", label: "授权时间", width: 160 },
			{ prop: "updateTime", label: "更新时间", width: 260 },
			{ prop: "lastInteractTime", label: "末次交互", width: 260 },
			{ prop: "sysInfo", label: "系统信息", width: 90, fixed: "right" },
			{ prop: "license", label: "授权信息", width: 100, fixed: "right" },
			{ prop: "operation", label: "操作", width: 70, fixed: "right" }
		];
		const saveConfig = () => {
			licenseMachineModify({ id: detailDialog.id, license: JSON.parse(detailDialog.detail) }).then(res => {
				let ok = showTips(res.code, "修改机器授权", res.message);
				if (ok) {
					detailDialog.visible = false;
					proTable.value.getTableList();
				}
			});
		};
		const modName = async (row: any) => {
			ElMessageBox.prompt("", "修改名字", {
				confirmButtonText: "确认",
				cancelButtonText: "取消",
				inputValue: row.name,
				inputPlaceholder: "请输入名字"
			})
				.then(async ({ value }) => {
					let { code, message } = await machineInfoModify({ id: row.id, name: value });
					let ok = showTips(code, "修改名字", message);
					if (ok) {
						proTable.value.getTableList();
					}
				})
				.catch(() => {});
		};
		const saveAdd = () => {
			if (!addDialog.name || !addDialog.machineId) {
				showMsg("请填写参数", MessageType.warning);
				return;
			}

			machineAdd({ name: addDialog.name, machineId: addDialog.machineId }).then(res => {
				let ok = showTips(res.code, detailDialog.title, res.message);
				if (ok) {
					addDialog.visible = false;
					proTable.value.reset();
				}
			});
		};
		return () => {
			return (
				<div class="machine-page">
					{detailDialog.visible ? (
						<DialogBox
							v-model:visible={detailDialog.visible}
							width="900"
							title={detailDialog.title}
							hideFooter={detailDialog.title == "系统信息"}
							onConfirm={saveConfig}
						>
							<JsonEditerVue v-model:data={detailDialog.detail} class="flex-1" style="height:600px;width:100%" />
						</DialogBox>
					) : (
						""
					)}
					<DialogBox v-model:visible={addDialog.visible} width="600" title="新增机器" onConfirm={saveAdd}>
						<el-form label-width="70px">
							<el-form-item label="名字">
								<el-input v-model={addDialog.name} placeholder="请输入名字" />
							</el-form-item>
							<el-form-item label="机器ID">
								<el-input v-model={addDialog.machineId} placeholder="请输入机器ID" />
							</el-form-item>
						</el-form>
					</DialogBox>
					<ProTable
						ref={proTable}
						title={btnList.value.length ? "" : "授权机器"}
						columns={columns}
						requestApi={getTableList}
						initParam={initParam}
						searchCol={4}
						dataCallback={dataCallback}
					>
						{{
							tableHeader: (scope: any) => {
								return btnList.value
									?.filter((item: any) => item.path != "del")
									?.map((item: any) => {
										return (
											<el-button onClick={() => clickBtn(item.path, scope)} type={item.btnClass}>
												<i class={`iconfont ${item.icon}`}></i>
												{item.menuName}
											</el-button>
										);
									});
							},
							machineId: (scope: any) => {
								return (
									<div
										class="truncate cursor-pointer primary-color"
										title="查看详情"
										onClick={() => gotoPage(RouterPath.authority, { machineId: scope.row.machineId })}
									>
										{scope.row.machineId}
									</div>
								);
							},
							name: (scope: any) => {
								return (
									<div
										class="truncate cursor-pointer primary-color"
										title="修改名字"
										onClick={() => {
											modName(scope.row);
										}}
									>
										{scope.row.name || "--"}
									</div>
								);
							},
							updateTime: (scope: any) => {
								return dayjs(scope.row.updateTime).format("YYYY-MM-DD HH:mm:ss");
							},
							lastInteractTime: (scope: any) => {
								return dayjs(scope.row.lastInteractTime).format("YYYY-MM-DD HH:mm:ss");
							},
							status: (scope: any) => {
								return licenseStatusType.filter((item: any) => item.value == scope.row.status)[0].label;
							},
							expired: (scope: any) => {
								return scope.row.license.app.ssiot.authority.expired.value || "--";
							},
							sysInfo: (scope: any) => {
								return (
									<el-link
										type="primary"
										link
										onClick={() => {
											clickBtn("sysInfo", scope.row);
										}}
									>
										查看
									</el-link>
								);
							},
							license: (scope: any) => {
								return (
									<>
										<el-link
											type="primary"
											link
											onClick={() => {
												clickBtn("detail", scope.row);
											}}
										>
											编辑
										</el-link>
										<el-link
											type="primary"
											link
											onClick={() => {
												clickBtn("download", scope.row);
											}}
										>
											下载
										</el-link>
									</>
								);
							},
							operation: (scope: any) => {
								return (
									<>
										{btnList.value.map((item: any) => {
											return item.path == "del" ? (
												<el-link type="danger" link class="iconfont icontrash-2" onClick={() => clickBtn(item.path, scope.row)}>
													删除
												</el-link>
											) : (
												""
											);
										})}
									</>
								);
							}
						}}
					</ProTable>
				</div>
			);
		};
	}
});
